/*---------------------------------------------------------------------------------------------
 *  Copyright (c) kylinIDETeam. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

import 'vs/css!./media/deploy';
import 'vs/base/browser/ui/codicons/codiconStyles'; // make sure codicon css is loaded
// import { localize } from 'vs/nls';
import { ipcRenderer } from 'vs/base/parts/sandbox/electron-sandbox/globals';
import { DeployWindowConfiguration } from 'vs/platform/issue/common/deploy';
import { IpcRendererEvent } from 'vs/base/parts/sandbox/electron-sandbox/electronTypes';

class deployWindow {

	onlineInstallRadio: HTMLElement | null = null;
	localInstallRadio: HTMLElement | null = null;
	justDownloadRadio: HTMLElement | null = null;
	notNowRadio: HTMLElement | null = null;
	onlineUpdateConfigRadio: HTMLElement | null = null;
	nextBtn: HTMLButtonElement | null;
	prevBtn: HTMLButtonElement | null;

	onlineInstallTabArray: string[] = ["homepage", "waitTab", "onlineInstallTab1", "onlineInstallTab2", "onlineInstallTab3", "onlineInstallTab4"];
	onlineInstallTabArrayIndex = 0;
	justDownLoadTabArray = ["first", "waitTab", "onlineInstallTab1", "onlineInstallTab2", "justDownloadTab1", "justDownloadTab2", "justDownloadTab3"];
	justDownLoadTabArrayIndex = 0;
	localInstallTabArray = ["first", "localInstallTab1", "localInstallTab2", "localInstallTab3", "localInstallTab4", "localInstallTab5"];
	localInstallTabArrayIndex = 0;
	firstClassList: any = {};
	currentTab = 0;
	finishFlag = -1;
	logPath = "";

	//用来标识程序结束完成
	gExtDownNum = 0;
	gSoftInstNum = 0;
	gExtInst = 0;
	extAddressPath = '';
	reloadWindowFlag = 0;

	extInstallState = new Map();
	extMap = {};
	extDownloadDoneCounter = 0;
	extInstallDoneCounter = 0;
	logShow = 0;
	progressNum = 0;
	downState = new Map();
	configList: { [key: string]: any } = {};
	extList: any[] = [];
	depList: any[] = [];
	scriptList: any[] = [];
	configData = [];

	nextBtnInvokeCheck: EventInvokeCheck | undefined;

	// 创建监听器
	listenerInit = async (event: IpcRendererEvent, msg: any) => {
		{
			console.log("receive: kylinide.installWizard.init");
			if (msg.type === "finish") {
				if (this.nextBtn) {
					this.nextBtn.innerText = "结束";
					this.nextBtn.disabled = false;
				}
			}
		}
	};
	listenerMsg = async (event: IpcRendererEvent, msg: any) => {
		console.log("receive: kylinide.installWizard.msg");
		//数据处理
		if (msg.type == "extStartDownload") {
			console.log("receive: kylinide.installWizard.msg:extStartDownload  " + msg.extName);
			this.extMap = msg.extMap;
			this.extInstallState.set(msg.extName, 1);
		}
		else if (msg.type == "downloadExtDone") {
			console.log("receive: kylinide.installWizard.msg:downloadExtDone  " + msg.extName);
			this.extDownloadDoneCounter++;
			const installMsg = {
				type: "installExt",
				extList: this.extList,
				depList: this.depList,
				downloadDone: msg.fileName,
				extName: msg.extName
			};
			this.extInstallState.set(msg.extName, 2);
			console.log("render send kylinide.installWizard.msg.process,installExt");
			ipcRenderer.send("kylinide.installWizard.msg.process", installMsg);
		}
		else if (msg.type == "extInstalled") {
			this.progressNum++;
			const extName = this.getKeyByValue(msg.extFileName, this.extMap);
			console.log("receive: kylinide.installWizard.msg:extInstalled  " + extName);
			this.extInstallDoneCounter++;
			this.extInstallState.set(extName, 12);
		}
		else if (msg.type == "extInstalledFail") {
			console.log("receive: kylinide.installWizard.msg:extInstalledFail  " + msg.extName);
			this.progressNum++;
			this.extInstallState.set(msg.extName, 3);
		}
		else if (msg.type == "downloadExtFail") {
			this.progressNum++;
			// const extName = getKeyByValue(msg.fileName, extMap);
			console.log("receive: kylinide.installWizard.msg:downloadExtFail  " + msg.extName);
			this.extInstallState.set(msg.extName, 4);
		}
		else if (msg.type == "depStartInstall") {
			console.log("receive: kylinide.installWizard.msg:depStartInstall");
			if (msg.depName === "depStartInstall") {
				let preElement = document.getElementById("installLogPre");
				preElement!.innerHTML = "";

				const messageData = {
					// url: utils.get_g_index_url(),
					// dst: utils.configDir()
				}
				//联网检查是否有合适的文件
				await ipcRenderer.invoke('kylinide.installWizard.checkInstall', messageData);
			}
			else {
				this.extInstallState.set(msg.depName, 11);
			}
		}
		else if (msg.type == "depInstallSucc") {
			console.log("receive: kylinide.installWizard.msg:depInstallSucc");
			this.progressNum++;
			this.extInstallState.set(msg.depName, 12);
			this.checkScripts(msg);
		}
		else if (msg.type === "depInstallFail") {
			console.log("receive: kylinide.installWizard.msg:depInstallFail");
			this.progressNum++;
			this.extInstallState.set(msg.depName, 3);
			this.checkScripts(msg);
		}
		else if (msg.type === "installLogPre") {
			console.log("receive: kylinide.installWizard.msg:installLogPre");
			let preElement = document.getElementById("installLogPre");
			let formattedDoc = preElement!.innerHTML;
			formattedDoc += msg.data;
			preElement!.innerHTML = formattedDoc;
			preElement!.scrollTop = preElement!.scrollHeight;
		}
		else if (msg.type === "extInstallLogPre") {
			console.log("receive: kylinide.installWizard.msg:extInstallLogPre");
			let preElement = document.getElementById("extInstallLogPre");
			let formattedDoc = preElement!.innerHTML;
			formattedDoc += msg.data;
			preElement!.innerHTML = formattedDoc;
			preElement!.scrollTop = preElement!.scrollHeight;
		}
		else if (msg.type === "extDownloadInit") {
			console.log("receive: kylinide.installWizard.msg:extDownloadInit");
			ipcRenderer.send('kylinide.installWizard.downloadExt', {
				extAddressPath: this.extAddressPath,
				configList: this.configList
			});
		}
		else if (msg.type === "scriptExecFail") {
			console.log("receive: kylinide.installWizard.msg:scriptExecFail");
			this.progressNum++;
			this.extInstallState.set(msg.depName, 16);
		}
		else if (msg.type === "scriptExecSucc") {
			console.log("receive: kylinide.installWizard.msg:scriptExecSucc");
			this.progressNum++;
			this.extInstallState.set(msg.depName, 15);
		}
		else if (msg.type === "cancelinstall") {
			console.log("receive: kylinide.installWizard.msg:cancelinstall");
			for (const [key, value] of this.extInstallState) {
				if (key === undefined) {
					console.log("cancel install: key is undefined");
					continue;
				}
				console.log("cancel install:" + key + " 状态：" + value);
				if (value === 0 || value === 1) {
					this.extInstallState.set(key, 4);
				}
			}
		}
		let dTpreElement = document.getElementById("detailInstallPre");
		dTpreElement!.innerHTML = '';
		let dTformattedDoc = '';

		console.log("progressNum:" + this.progressNum + " extInstallState.size:" + this.extInstallState.size)
		if (this.extInstallState.size > 0) {
			if (this.finishFlag !== 0) {
				let progressViews = document.getElementsByClassName("progress-view") as HTMLCollectionOf<HTMLProgressElement>;
				progressViews[0].value = (this.progressNum / this.extInstallState.size) * 100;
				document.getElementsByClassName("progressinfoValue")[0].innerHTML = ((this.progressNum / this.extInstallState.size) * 100).toFixed(2) + "%";
			}
		}

		for (const [key, value] of this.extInstallState) {
			if (key === undefined) continue;
			switch (value) {
				case 0:
					dTformattedDoc += "<img class='startHighlightImg'><span class='startHighlight'>" + key + "准备中...</span><br>";
					break;
				case 1:
					dTformattedDoc += "<img class='startHighlightImg'><span class='startHighlight'>" + key + "开始下载</span><br>";
					break;
				case 2:
					dTformattedDoc += "<span class='downloadHighlight'>" + key + "下载完成</span><br>";
					break;
				case 3:
					dTformattedDoc += "<span class='depfailHighlight'>" + key + "安装失败</span><br>";
					break;
				case 4:
					dTformattedDoc += "<span class='depfailHighlight'>" + key + "下载失败</span><br>";
					break;
				case 11:
					dTformattedDoc += "<span class='downloadHighlight'>" + key + "开始安装</span><br>";
					break;
				case 12:
					dTformattedDoc += "<span class='installedHighlight'>" + key + "安装完成</span><br>";
					break;
				case 15:
					dTformattedDoc += "<span class='installedHighlight'>" + key + "脚本执行成功</span><br>";
					break;
				case 16:
					dTformattedDoc += "<span class='depfailHighlight'>" + key + "脚本执行失败</span><br>";
					break;
				default:
					// 处理默认情况
					break;
			}
		}
		dTpreElement!.innerHTML = dTformattedDoc;

		let flag = 0;
		//检查所有处理是否已完成
		if (msg.type == "extInstalled" || msg.type == "extInstalledFail"
			|| msg.type == "downloadExtFail" || msg.type == "depInstallSucc"
			|| msg.type == "depInstallFail" || msg.type == "scriptExecFail" || msg.type == "scriptExecSucc") {
			for (const [key, value] of this.extInstallState) {
				if (key === undefined) continue;
				switch (value) {
					case 0: flag++;
						break;
					case 1: flag++;
						break;
					case 2:
						flag++;
						break;
					case 11:
						flag++
						break;
					default:
						// 处理默认情况
						break;
				}
			}

			if (flag === 0) {
				//检查所有的开发场景是否都安装成功
				let writeKeyJson = [];
				let showContext = "";
				showContext += "安装结束\n";
				for (let key in this.configList) {
					console.log("end:" + key);
					//检查某个开发场景的软件包是否全部安装成功
					let tmp = this.getNameFromKey(key);
					let installflag = this.checkKeyInstalledInfo(key, this.configList, this.extInstallState);
					if (installflag === 1) {
						writeKeyJson.push(key);
						showContext += "<span class='installedHighlight'>" + tmp + "安装成功</span><br>";
					} else if (installflag === 0) {
						showContext += "<span class='FailPartHighlight'>" + tmp + "未全部安装成功</span><br>";
					} else if (installflag === -1) {
						showContext += "<span class='depfailHighlight'>" + tmp + "安装失败</span><br>";
					}
				}
				if (writeKeyJson.length > 0) {
					ipcRenderer.send("kylinide.installWizard.init", { type: "writeKey", keys: writeKeyJson });
				}
				showContext += "点击结束按钮退出开发环境快速部署\n";
				let allSuccess = this.checkAllInstalledSucc(this.extInstallState);
				this.goFinish(showContext, false, allSuccess);
				console.log("安装结束");
			}
		}
		// preElement.scrollTop = preElement.scrollHeight;
	};
	listenerRemoveFileLister = (event: IpcRendererEvent, msg: any) => {
		console.log("receive: kylinide.installWizard.removeFileLister")
		if (msg.type == "installFile") {
			ipcRenderer.send("kylinide.installWizard.removeFileLister", { type: "installFile" })
		} else if (msg.type == "extFile") {
			ipcRenderer.send("kylinide.installWizard.removeFileLister", { type: "extFile" })
		} else if (msg.type == "pkgFile") {
			ipcRenderer.send("kylinide.installWizard.removeFileLister", { type: "pkgFile" })
		}
	};
	listenerCancelInstall = (event: IpcRendererEvent, msg: any) => {
		console.log("receive: kylinide.installWizard.cancelInstall")
		if (msg.type == "cancelinstall") {
			let showContext = '';
			showContext += "取消安装，中断安装过程\n";
			//检查安装情况
			let writeKeyJson = [];
			for (let key in this.configList) {
				console.log("end:" + key);
				//检查某个开发场景的软件包是否全部安装成功，或者部分安装成功，或者全部安装失败
				let tmp = this.getNameFromKey(key);
				let installflag = this.checkKeyInstalledInfo(key, this.configList, this.extInstallState);
				if (installflag === 1) {
					writeKeyJson.push(key);
					showContext += "<span class='installedHighlight'>" + tmp + "安装成功</span><br>";
				} else if (installflag === 0) {
					showContext += "<span class='FailPartHighlight'>" + tmp + "未全部安装成功</span><br>";
				} else if (installflag === -1) {
					showContext += "<span class='depfailHighlight'>" + tmp + "安装失败</span><br>";
				}
			}
			if (writeKeyJson.length > 0) {
				ipcRenderer.send("kylinide.installWizard.init", { type: "writeKey", keys: writeKeyJson });
			}
			showContext += "点击结束按钮退出开发环境快速部署\n"
			let allSuccess = this.checkAllInstalledSucc(this.extInstallState);
			if (!allSuccess) {
				this.goFinish(showContext, true, allSuccess);
			}
			console.log("安装结束：取消");
		}
	};
	listenerAuth = (event: IpcRendererEvent, msg: any) => {
		console.log("receive: kylinide.installWizard.Auth")
		if (msg.type == "pkgNotAuth") {
			let showContext = '';
			showContext += "授权失败，结束安装\n";
			showContext += "点击结束按钮退出开发环境快速部署\n";
			this.goFinish(showContext, true, false);

			console.log("安装结束：授权失败")
		}
	};
	listenerInitData = (event: IpcRendererEvent, msg: any) => {
		console.log("receive: kylinide.installWizard.initData")
		if (!msg.isFirstLoad) {
			this.notNowRadio!.style.display = 'none';
			document.getElementById('lablenotNow')!.style.display = 'none';
		}
		this.reset();
		this.logPath = msg.logPath;
	};

	// private nativeHostService: INativeHostService;
	// private productService: IProductService;
	constructor(windowId: number) {
		// const mainProcessService = new ElectronIPCMainProcessService(windowId);
		// this.nativeHostService = new NativeHostService(windowId, mainProcessService) as INativeHostService;

		this.onlineInstallRadio = document.getElementById("onlineInstall");
		this.localInstallRadio = document.getElementById("localInstall");
		this.justDownloadRadio = document.getElementById("justDownload");
		this.notNowRadio = document.getElementById("notNow");
		this.onlineUpdateConfigRadio = document.getElementById("onlineUpdateConfig");
		this.nextBtn = document.getElementById("nextStep") as HTMLButtonElement;
		this.prevBtn = document.getElementById("prevStep") as HTMLButtonElement;
		this.showTab(this.currentTab);
		this.removeAllListeners();
		this.registerEventListener();
		this.reloadWindowFlag = 0;
	}

	// setHeader() {
	// 	// Minimize
	// 	var titleRight: HTMLElement | null;
	// 	titleRight = document.getElementById("header-right");
	// 	if (titleRight) {
	// 		const minimizeIcon = append(titleRight, $('window-minimize' + ThemeIcon.asCSSSelector(Codicon.chromeMinimize)));
	// 		const closeIcon = append(titleRight, $('div.window-icon.window-close' + ThemeIcon.asCSSSelector(Codicon.chromeClose)));
	// 	}
	// }
	showTab(n: number) {
		let x = document.getElementsByClassName('tab') as HTMLCollectionOf<HTMLElement>;
		x[n].style.display = 'flex';
		//... and fix the Previous/Next buttons:
		if (n === 0) {
			this.prevBtn!.style.display = 'none';
		} else {
			this.prevBtn!.style.display = 'inline';
		}
		if (n === (x.length - 1)) {
			this.nextBtn!.innerHTML = '结束';
		} else {
			this.nextBtn!.innerHTML = "下一步";
		}
	}

	custom_print(msg: string) {
		// console.log("custom_print ==> " + msg);
		console.log(msg);
	}

	reset() {
		this.onlineInstallTabArrayIndex = 0;
		this.justDownLoadTabArrayIndex = 0;
		this.localInstallTabArrayIndex = 0;
		this.firstClassList = {};
		this.currentTab = 0;
		this.finishFlag = -1;

		this.gExtDownNum = 0;
		this.gSoftInstNum = 0;
		this.gExtInst = 0;
		this.extAddressPath = '';

		this.extInstallState = new Map();
		this.extMap = {};
		this.extDownloadDoneCounter = 0;
		this.extInstallDoneCounter = 0;
		this.logShow = 0;
		this.progressNum = 0;
		this.downState = new Map();
		this.configList = {};
		this.extList = [];
		this.depList = [];
		this.scriptList = [];
		this.configData = [];

		this.nextBtnInvokeCheck = new EventInvokeCheck(300);
		console.log("reset complete");
	}

	goFinish(showContext: string, useFinishHtml: boolean, success: boolean) {
		this.finishFlag = 0;
		let preFinish = document.getElementById("finishPage");
		showContext += "点击右上方切换输出按钮查看安装列表详情";

		if (useFinishHtml) {
			let text = preFinish!.innerHTML;
			text += showContext;
			preFinish!.innerHTML = text;
		} else {
			preFinish!.innerHTML = showContext;
		}

		preFinish!.style.display = 'block';
		document.getElementById("installLogPre")!.style.display = 'none';
		document.getElementById("detailInstallPre")!.style.display = 'none';
		document.getElementById("extInstallLogPre")!.style.display = 'none';
		document.getElementById("progressInfoCancel")!.style.display = 'none';
		document.getElementById("labelprocessdetail")!.innerHTML = "安装结果";

		if (success) {
			document.getElementById("progressInfoFinish")!.style.display = 'inline-block';
			// 选择包含进度条的元素，并设置伪元素样式
			var style = document.createElement('style');
			style.textContent = ".progress-view::-webkit-progress-value { background-color: #1AC465; }";
			document.head.appendChild(style);
		} else {
			document.getElementById("progressInfoFinishFail")!.style.display = 'inline-block';
			// 选择包含进度条的元素，并设置伪元素样式
			var style = document.createElement('style');
			style.textContent = ".progress-view::-webkit-progress-value { background-color: red; }";
			document.head.appendChild(style);
		}

		this.nextBtn!.innerText = "结束";
		this.nextBtn!.disabled = false;
		this.logShow = 3;
		ipcRenderer.send("kylinide.installWizard.removeFileLister", { type: "extFile" });
		ipcRenderer.send("kylinide.installWizard.removeFileLister", { type: "pkgFile" });
		ipcRenderer.send("kylinide.installWizard.removeFileLister", { type: "installFile" });
		ipcRenderer.send("kylinide.installWizard.finish", { type: "finish" });
		this.removeAllListeners();
	}

	async nextPrev(n: number) {

		this.nextBtn!.disabled = true;
		this.prevBtn!.disabled = true;

		// This function will figure out which tab to display
		// let x = document.getElementsByClassName('tab');
		// Exit the function if any field in the current tab is invalid:
		// if (n == 1 && !validateForm()) return false;
		// if (n < 1) return false;
		//TODO 下一步校验
		//跳过
		if (this.notNowRadio && this.notNowRadio instanceof HTMLInputElement && this.notNowRadio.checked) {
			this.justDownLoadTabArrayIndex = 0;
			this.localInstallTabArrayIndex = 0;
			// console.log('renderer send kylinide.installWizard.skipWizard');
			ipcRenderer.send('kylinide.installWizard.closeWizard', { type: "skip" });
		} else if (this.onlineInstallRadio && this.onlineInstallRadio instanceof HTMLInputElement && this.onlineInstallRadio.checked) {
			this.justDownLoadTabArrayIndex = 0;
			this.localInstallTabArrayIndex = 0;

			this.custom_print(this.onlineInstallTabArray[this.onlineInstallTabArrayIndex]);

			if (this.onlineInstallTabArray[this.onlineInstallTabArrayIndex] === "onlineInstallTab1") {
				//获取radio的值
				console.log("nextPrev onlineInstallTab1");
				let select = "local";
				if (this.onlineUpdateConfigRadio && this.onlineUpdateConfigRadio instanceof HTMLInputElement && this.onlineUpdateConfigRadio.checked) {
					select = "update"
				}
				const data = {
					type: "configSelect",
					select: select
				}

				console.log("renderer send kylinide.installWizard.init.configSelect");
				let result = await ipcRenderer.invoke('kylinide.installWizard.init.configSelect', data);
				if (result === void 0) {
					return;
				}
				this.prevBtn!.disabled = true;
				const parentdiv = document.getElementById('osInfo') as HTMLDivElement;
				const parentdivshow = document.getElementById('osInfoShow') as HTMLDivElement;
				parentdiv.innerHTML = "";
				parentdivshow.innerHTML = "";
				let osrelease;
				if (!result.osrelease) {
					osrelease = `<h3>操作系统信息</h3><p>操作系统检测脚本运行失败，未成功检测到操作系统类型</p>`
				} else {
					osrelease = `<h3>操作系统信息</h3><p>已检测到当前操作系统信息为：<span>${result.osrelease}</span></p>`;
				}
				parentdiv.innerHTML = osrelease;
				let dataSys = "";
				let osdiv;
				osdiv = `<p>判断依据:</p><div><p>cat  ${result.osFile}</p>`;
				dataSys = `${result.osData}`
				if (osdiv == "" && dataSys == "") {
					parentdivshow.innerHTML = "读取操作系统信息失败";
				} else {
					parentdivshow.innerHTML = `${osdiv}<p>${dataSys}</p></div>`;
				}

			} else if (this.onlineInstallTabArray[this.onlineInstallTabArrayIndex] === "onlineInstallTab2") {
				const data = {
					type: "configGetValue",
					class: "install"
				}
				console.log("nextPrev onlineInstallTab2");
				let result = await ipcRenderer.invoke('kylinide.installWizard.init.configGetValue', data);
				if (result === void 0) {
					console.log("kylinide.installWizard.init.configGetValue result is void");
					this.prevBtn!.disabled = false;
					return;
				}
				console.log("kylinide.installWizard.init configGetValue depInfoData:" + result.depInfoData)
				this.gExtDownNum = 0;
				this.gSoftInstNum = 0;
				this.gExtInst = 0;
				this.progressNum = 0;

				let depInfoData = result.depInfoData;
				let selectAll = document.getElementById("selectAll");
				if (selectAll === null)
					this.setFisrtClass(depInfoData, result.selectKey);
				this.extAddressPath = result.extAddressPath;

			} else if (this.onlineInstallTabArray[this.onlineInstallTabArrayIndex] === "onlineInstallTab3") {
				const checkboxForm = document.getElementById("checkboxForm");
				console.log("nextPrev onlineInstallTab3");
				// 获取所有选中的复选框
				let selectedCheckboxes = checkboxForm!.querySelectorAll('input[type="checkbox"]:checked');
				let checkSelectedValues = [];
				this.extInstallState.clear();
				this.extDownloadDoneCounter = 0;
				this.extInstallDoneCounter = 0;
				this.progressNum = 0;

				for (var item of selectedCheckboxes) {
					var checkbox = item as HTMLInputElement;
					if (checkbox.value !== "JavaScript_key" && checkbox.value !== "selectAll") {
						checkSelectedValues.push(checkbox.value);
					}
				}

				//去重
				console.log("selectedCheckboxes.length:" + selectedCheckboxes.length);

				for (const val of this.depList) {
					this.extInstallState.set(val, 0);
				}

				for (const val of this.extList) {
					this.extInstallState.set(val, 0);
				}

				for (let obj of this.scriptList) {
					if (obj["file_name"]) {
						this.extInstallState.set(obj["file_name"], 0);
					}
				}

				console.log("extInstallState.size" + this.extInstallState.size);
				let progress_view = document.getElementsByClassName("progress-view") as HTMLCollectionOf<HTMLProgressElement>;
				progress_view[0].value = 0;
				document.getElementsByClassName("progressinfoValue")[0].innerHTML = "0%";
				document.getElementById("progressInfoCancel")!.style.display = 'inline-block';
				document.getElementById("progressInfoFinish")!.style.display = 'none';
				document.getElementById("progressInfoFinishFail")!.style.display = 'none';
				document.getElementById("detailInstallOutputLogInfo")!.innerHTML = "log目录:" + this.logPath;

				let extPreElement = document.getElementById("extInstallLogPre");
				extPreElement!.innerHTML = "";

				const installPkgMsg = {
					type: "installPkg",
					configList: this.configList,
					extList: this.extList,
					depList: this.depList,
					scriptList: this.scriptList,
					checkSelectedValues: checkSelectedValues
				}

				ipcRenderer.send('kylinide.installWizard.msg.process', installPkgMsg);
				console.log("renderer send kylinide.installWizard.msg.process", JSON.stringify(installPkgMsg));
				ipcRenderer.send('kylinide.installWizard.init', { type: "writeJson", });
				console.log("renderer send kylinide.installWizard.init writeJson");
			} else if (this.onlineInstallTabArray[this.onlineInstallTabArrayIndex] === "onlineInstallTab4") {
				this.removeAllListeners();
				ipcRenderer.send('kylinide.installWizard.closeWizard', { type: "close" });
				console.log("renderer send kylinide.installWizard.closeWizard", 'close');
				if (this.reloadWindowFlag) {
					ipcRenderer.send('kylinide.installWizard.reloadwindow');
				}
				this.custom_print("nextPrev onlineInstallTab4");
				return;
			}
			if (this.onlineInstallTabArrayIndex < this.onlineInstallTabArray.length - 1) {
				this.custom_print("this.onlineInstallTabArrayIndex < this.onlineInstallTabArray.length - 1");
				if (this.onlineInstallTabArrayIndex == 0) {
					this.removeStepIndicator();
					this.createStepIndicator(this.onlineInstallTabArray.length - 1, 0);

					console.log("renderer send kylinide.installWizard.init httpVerify");
					let result = await ipcRenderer.invoke('kylinide.installWizard.init.httpVerify');
					if (result === void 0) {
						this.prevBtn!.disabled = false;
						this.nextBtn!.disabled = false;
						console.log("kylinide.installWizard.init.httpVerify result is void");
						return;
					}

					let preTab = document.getElementById(this.onlineInstallTabArray[this.onlineInstallTabArrayIndex]) as HTMLDivElement;
					if (preTab) {
						preTab.style.display = 'none';
					}
					this.onlineInstallTabArrayIndex = this.onlineInstallTabArrayIndex + 1;
					this.showTabFromIndex(this.onlineInstallTabArray, this.onlineInstallTabArrayIndex);
					let configData = await ipcRenderer.invoke('kylinide.installWizard.init.configVersify', { type: "configVersify" });
					console.log("kylinide.installWizard.init configVersify ");
					if (configData === void 0) {
						this.prevBtn!.disabled = false;
						console.log("kylinide.installWizard.init.configVersify result is void");
						return;
					}
					// console.log("kylinide.installWizard.init configVersify result:" + JSON.stringify(configData));
					// console.log(configData.type + " " + configData.selectPageShow + " " + configData.message);
					if (configData.selectPageShow) {
						const onlineUpdateConfig = document.getElementById("onlineUpdateConfig") as HTMLInputElement;
						const onlineLocalConfig = document.getElementById("onlineLocalConfig") as HTMLInputElement;
						const parentdiv = document.getElementById('onlinewarning') as HTMLDivElement;
						parentdiv.innerHTML = "";
						if (configData.selectPageShow == 1) {
							if (onlineLocalConfig && onlineUpdateConfig && parentdiv) {
								onlineLocalConfig.disabled = true;
								onlineUpdateConfig.checked = true;
								parentdiv.innerHTML = configData.message;
							}

						} else if (configData.selectPageShow == 2 || configData.selectPageShow == 3) {
							onlineLocalConfig.checked = true;
							onlineUpdateConfig.disabled = true;
							parentdiv.innerHTML = configData.message;
						} else if (configData.selectPageShow == 4) {
							onlineUpdateConfig.checked = true;
							parentdiv.innerHTML = configData.message;
						}
					}
					this.nextPrev(1);

				} else {
					this.custom_print("nextPrev this.onlineInstallTabArrayIndex != 0")

					if (this.onlineInstallTabArray[this.onlineInstallTabArrayIndex] === "onlineInstallTab2") {
						let checkboxForm = document.getElementById("checkboxForm");
						//设置下一步按钮显示状态
						let selectedCheckboxes = checkboxForm?.querySelectorAll('input[type="checkbox"]:checked');
						// console.log("aaa+" + selectedCheckboxes.length);
						if (selectedCheckboxes && selectedCheckboxes.length > 1) {
							this.nextBtn!.disabled = false;
						} else {
							this.nextBtn!.disabled = true;
						}
					} else {
						this.nextBtn!.disabled = false;
					}

					let preTab = document.getElementById(this.onlineInstallTabArray[this.onlineInstallTabArrayIndex]) as HTMLDivElement;
					preTab.style.display = 'none';
					this.onlineInstallTabArrayIndex = this.onlineInstallTabArrayIndex + n;
					this.showTabFromIndex(this.onlineInstallTabArray, this.onlineInstallTabArrayIndex);
					if (this.onlineInstallTabArray[this.onlineInstallTabArrayIndex] !== "onlineInstallTab2")
						this.prevBtn!.disabled = false;
				}
			}
			if (this.onlineInstallTabArray[this.onlineInstallTabArrayIndex] === "onlineInstallTab4") {
				console.log("onlineInstallTab4 last");
				this.prevBtn!.disabled = true;
				this.nextBtn!.disabled = true;
				this.nextBtn!.innerHTML = "结束";
			}
		}
	}

	createStepIndicator(length: number, currentIndex: number) {
		var indicatorDiv = document.getElementById('indicator');
		while (indicatorDiv!.firstChild) {
			indicatorDiv!.removeChild(indicatorDiv!.firstChild);
		}
		for (let i = 0; i < length; i++) {
			let indicatorItem = document.createElement('div');
			indicatorItem.classList.add('indicator-item');
			indicatorDiv!.appendChild(indicatorItem);
		}
		this.fixStepIndicator(currentIndex);
	}
	removeStepIndicator() {
		var indicatorDiv = document.getElementById('indicator');
		while (indicatorDiv!.firstChild) {
			indicatorDiv!.removeChild(indicatorDiv!.firstChild);
		}
	}
	fixStepIndicator(index: number) {
		var indicatorDiv = document.getElementById('indicator');
		if (index < 0 || index > indicatorDiv!.children.length - 1)
			return;
		let activeItem = indicatorDiv!.querySelector('.active');
		if (activeItem) {
			activeItem.classList.remove('active');
		}
		// indicatorDiv!.children[index].classList.add('active');
		for (let i = 0; i < indicatorDiv!.children.length; i++) {
			if (i == index) {
				indicatorDiv!.children[i].classList.add('active');
				continue;
			}
			if (i < index) {
				indicatorDiv!.children[i].classList.add('active-before');
			} else {
				indicatorDiv!.children[i].classList.remove('active-before');
			}
		}
	}

	showTabFromIndex(tabArray: string[], Index: number) {
		let tab = document.getElementById(tabArray[Index]) as HTMLDivElement;
		tab.style.display = 'flex';
		if (Index === 0) {
			if (this.prevBtn)
				this.prevBtn.style.display = 'none';
		} else {
			if (this.prevBtn)
				this.prevBtn.style.display = 'inline';
		}
		if (Index === (tabArray.length - 1)) {
			if (this.nextBtn) { this.nextBtn.innerHTML = "结束" }
		} else {
			if (this.nextBtn) { this.nextBtn.innerHTML = "下一步" }
		}
		if (Index === 0) {
			this.removeStepIndicator();
		}
		if (Index > 0) {
			this.fixStepIndicator(Index - 1);
		}
	}
	registerEventListener() {
		/**
		 * 窗口关闭按钮动作
		 */
		document.getElementById('closeBtn')?.addEventListener('click', () => {
			console.log('window closeBtn clicked');
			if (this.onlineInstallRadio instanceof HTMLInputElement && this.onlineInstallRadio!.checked
				&& this.onlineInstallTabArray[this.onlineInstallTabArrayIndex] == "onlineInstallTab4"
				&& this.finishFlag !== 0
			) {
				ipcRenderer.send('kylinide.installWizard.show', { type: "info", message: "正在进行安装操作，若关闭窗口，则需先点击取消按钮中断安装过程。", title: "提示" });
				//检查是否有进程正在安装，如果是，则提醒用户先点击取消安装，停止后台程序。然后再关闭程序
				// ipcRenderer.send('kylinide.installWizard.closeBefore', { type: "processterm" });
			}
			else {
				ipcRenderer.send('kylinide.installWizard.closeWizard', { type: "close" });
				this.removeAllListeners();
				if (this.reloadWindowFlag) {
					ipcRenderer.send('kylinide.installWizard.reloadwindow');
				}
			}
		});
		/**
	* 窗口最小化按钮动作
	*/
		document.getElementById('minwBtn')?.addEventListener('click', () => {
			console.log("render send kylinide.installWizard.minw");
			ipcRenderer.send('kylinide.installWizard.minw', { type: "minw" });
		});

		document.getElementById('helpLink')?.addEventListener('click', (e) => {
			e.preventDefault();
			console.log("render send kylinide.installWizard.helpLink");
			ipcRenderer.send('kylinide.installWizard.helpLink', { type: "helpLink" })
		});

		// document.getElementById('skipAll')?.addEventListener('click', () => {
		// 	console.log("render send kylinide.installWizard.skipWizard");
		// 	ipcRenderer.send('kylinide.installWizard.skipWizard');
		// });

		this.prevBtn!.addEventListener('click', () => {
			console.log('click prevStep');
			this.Prev(-1);
		});

		this.nextBtn!.addEventListener('click', () => {
			console.log('click nextStep');
			if (this.nextBtnInvokeCheck!.canInvoke()) {
				this.nextPrev(1);
			}
		});
		document.getElementById('progressInfoCancel')?.addEventListener('click', () => {
			console.log('click cancel');
			// ipcRenderer.removeAllListeners('kylinide.installWizard.msg');
			ipcRenderer.send('kylinide.installWizard.msg.process', { type: "cancel" });
			console.log("render send kylinide.installWizard.msg.process:cancel");
		});
		/**
		 * 安装界面：安装详情显示/隐藏切换按钮
		 */
		document.getElementById("switchInstallOutput")?.addEventListener("click", () => {
			// 切换显示和隐藏
			console.log("switchInstallOutput clicked");
			const logPreElement = document.getElementById("installLogPre");
			const installPreElement = document.getElementById("detailInstallPre");
			const extLogPreElement = document.getElementById("extInstallLogPre");
			const finishPage = document.getElementById("finishPage");
			let logView = [installPreElement, logPreElement, extLogPreElement, finishPage];
			this.logShow++;
			if (this.logShow % (logView.length + this.finishFlag) == 0) {
				document.getElementById("labelprocessdetail")!.innerHTML = "安装列表详情";
				installPreElement!.style.display = "block";
				logPreElement!.style.display = "none";
				extLogPreElement!.style.display = "none";
				if (this.finishFlag > -1)
					finishPage!.style.display = "none";
			}
			else if (this.logShow % (logView.length + this.finishFlag) == 1) {
				if (this.depList.length > 0) {
					document.getElementById("labelprocessdetail")!.innerHTML = "系统软件安装详情";
					installPreElement!.style.display = "none";
					logPreElement!.style.display = "block";
					extLogPreElement!.style.display = "none";
					if (this.finishFlag > -1)
						finishPage!.style.display = "none";
				} else {
					this.logShow++;
				}

			}
			if (this.logShow % (logView.length + this.finishFlag) == 2) {
				document.getElementById("labelprocessdetail")!.innerHTML = "插件安装详情";
				installPreElement!.style.display = "none";
				logPreElement!.style.display = "none";
				extLogPreElement!.style.display = "block";
				if (this.finishFlag > -1)
					finishPage!.style.display = "none";
			} else if (this.logShow % (logView.length + this.finishFlag) == 3) {
				document.getElementById("labelprocessdetail")!.innerHTML = "安装结果";
				finishPage!.style.display = "block";
				installPreElement!.style.display = "none";
				logPreElement!.style.display = "none";
				extLogPreElement!.style.display = "none";
			}
		});

		ipcRenderer.on('kylinide.installWizard.init', this.listenerInit);
		ipcRenderer.on('kylinide.installWizard.msg', this.listenerMsg);
		ipcRenderer.on('kylinide.installWizard.removeFileLister', this.listenerRemoveFileLister);
		ipcRenderer.on('kylinide.installWizard.cancelInstall', this.listenerCancelInstall);
		ipcRenderer.on('kylinide.installWizard.Auth', this.listenerAuth);
		ipcRenderer.on('kylinide.installWizard.initdata', this.listenerInitData);
	}
	Prev(n: number) {
		if (this.onlineInstallRadio instanceof HTMLInputElement && this.onlineInstallRadio!.checked) {
			let tab = document.getElementById(this.onlineInstallTabArray[this.onlineInstallTabArrayIndex]);
			tab!.style.display = 'none';
			this.onlineInstallTabArrayIndex = this.onlineInstallTabArrayIndex + n;
			if (this.onlineInstallTabArray[this.onlineInstallTabArrayIndex] === 'waitTab') {
				document.getElementById('waitTab')!.style.display = 'none';
				this.onlineInstallTabArrayIndex = this.onlineInstallTabArrayIndex + n;
			}
			if (this.onlineInstallTabArray[this.onlineInstallTabArrayIndex] === 'onlineInstallTab2') {
				this.nextBtn!.disabled = false;
			}
			if (this.onlineInstallTabArray[this.onlineInstallTabArrayIndex] !== "onlineInstallTab1")
				this.prevBtn!.disabled = true;
			this.showTabFromIndex(this.onlineInstallTabArray, this.onlineInstallTabArrayIndex);
		}
	}

	setFisrtClass(depDataObject: any, jsonSelectKey: string[]) {
		var form = document.getElementById("checkboxForm");
		// var depDataObject = JSON.parse(fs.readFileSync(depPath, 'utf-8'));
		let lan = this.getLanguage();
		let firstClass = depDataObject['first_class_list'];
		this.firstClassList = firstClass;

		// 创建标签列表
		let labels = [];
		let firstClassVal = [];

		if (lan == 'zh-cn') {
			labels.push('全选');
			firstClassVal.push({ key: "selectAll", val: "全选" });
		}
		else {
			labels.push('Select All');
			firstClassVal.push({ key: "selectAll", val: "Select All" });
		}

		if (firstClass.hasOwnProperty("description")) {
			let value = firstClass["description"];
			if (lan == "zh-cn" && value.hasOwnProperty("zh_cn")) {
				document.getElementById("depOutDesc")!.innerHTML = value["zh_cn"];
			}
			else if (lan == "en" && value.hasOwnProperty("en")) {
				document.getElementById("depOutDesc")!.innerHTML = value["en"];
			}
		}

		let installedPkg = [];

		if (jsonSelectKey.length > 0) {
			if (document.getElementById('jsonSelectKey') !== null) {
				return;
			}
			const preE = document.createElement('div');
			preE.id = "jsonSelectKey";
			preE.classList.add('jsonSelectKey');
			let constent = "";
			let flag = 0;
			for (let i = 0; i < jsonSelectKey.length; i++) {
				if (firstClass.hasOwnProperty(jsonSelectKey[i])) {
					console.log("json:" + firstClass[jsonSelectKey[i]]['zh_cn']);
					flag++;
					constent += firstClass[jsonSelectKey[i]]['zh_cn'] + " ";
					installedPkg.push(firstClass[jsonSelectKey[i]]['zh_cn']);
				}
			}

			console.log("已安装包:" + constent);
			if (flag > 0)
				constent += "已安装，若再次勾选，将重新安装"
			preE.textContent = constent;
			document.getElementById("depOutDesc")?.insertAdjacentElement("afterend", preE);
		}


		for (let key in firstClass) {
			if (firstClass.hasOwnProperty(key)) {
				let value = firstClass[key];
				if (key == "description") continue;
				if (lan == "zh-cn" && value.hasOwnProperty("zh_cn")) {
					labels.push(value["zh_cn"]);
					firstClassVal.push({ key: key, val: value["zh_cn"] });
					console.log("firstClass:" + key + ":" + value["zh_cn"]);
				}
				else if (value.hasOwnProperty("en")) {
					labels.push(value["en"]);
					firstClassVal.push({ key: key, val: value["en"] });
				}

			}
		}


		//循环创建并添加标签到表单中
		firstClassVal.forEach(function (item) {
			// 创建label元素
			var label = document.createElement("div");
			label.className = "scenarioSelection";

			// 创建checkbox元素
			var checkbox = document.createElement("input");
			checkbox.type = "checkbox";
			checkbox.value = item.key;
			checkbox.id = item.key;

			checkbox.className = "checkbox"

			if (jsonSelectKey.indexOf(item.key) > -1) {
				checkbox.classList.add("checkboxselect");
			}

			if (checkbox.id === "JavaScript_key") {
				checkbox.checked = true;
				checkbox.disabled = true;
			}

			if (item.key === "selectAll") {
				checkbox.classList.add("selectAll");
			}

			console.log("选项 checkbox:" + checkbox.id + ":" + checkbox.className + ":" + checkbox.type + ":" + checkbox.classList.length + ":" + checkbox.value + ":" + checkbox.checked);
			// "==> checkbox:				selectAll			checkbox					checkbox selectAll		2								selectAll				false
			// "==> checkbox:				Remote_key			checkbox checkboxselect		heckbox					2								Remote_key				false
			// "==> checkbox:				C_key				checkbox					checkbox				1								C_key					false
			// "==> checkbox:				JAVA_key			checkbox checkboxselect		checkbox				2								JAVA_key				false
			// "==> checkbox:				Python3_key			checkbox checkboxselect		checkbox				2								Python3_key				false
			// "==> checkbox:				Go_key				checkbox					checkbox				1								Go_key					false
			// "==> checkbox:				JavaScript_key		checkbox					checkbox				1								JavaScript_key			true

			// 全选		   			checkbox selectAll
			// 非全选:已安装过的  	checkbox checkboxselect
			// 非全选:未安装过的  	checkbox

			// 创建label文本
			var labelTextNode = document.createElement("label");
			labelTextNode.setAttribute("for", item.key);
			labelTextNode.innerHTML = item.val;

			// 添加checkbox和label文本到label元素中
			label.appendChild(checkbox);
			label.appendChild(labelTextNode);

			// 添加label元素到表单中
			form!.appendChild(label);
			form!.appendChild(document.createElement("br"));
		});
		this.showDependences(depDataObject);
	}
	getLanguage() {
		return 'zh-cn'
	}

	updateDevSceneCheckState() {
		let selectAllVal = document.getElementById("selectAll") as HTMLInputElement;
		var checks = document.querySelectorAll(".scenarioSelection > input[type='checkbox']:not([value='selectAll'])");
		var allChecked = true;
		var allUnchecked = true;
		for (var item of checks) {
			var checkbox = item as HTMLInputElement;
			if (checkbox.value !== "JavaScript_key" && checkbox.checked) {
				allUnchecked = false;
			} else if (checkbox.value !== "JavaScript_key" && checkbox.checked == false) {
				allChecked = false;
			}
		}
		if (allChecked) {
			selectAllVal.checked = true;
			selectAllVal.indeterminate = false;
		} else if (allUnchecked) {
			selectAllVal.checked = false;
			selectAllVal.indeterminate = false;
		} else {
			selectAllVal.checked = false;
			selectAllVal.indeterminate = true;
		}
	}

	showDependences(arg: any) {
		this.configData = [];
		// this.configData.push(arg);
		var elements = document.getElementsByClassName("scenarioSelection");
		this.configList = {};
		let formattedDoc = '';

		let selectAllVal = document.getElementById("selectAll") as HTMLInputElement;
		var checks = document.querySelectorAll(".scenarioSelection > input[type='checkbox']:not([value='selectAll'])");
		selectAllVal.onclick = function () {
			for (var i = 0; i < checks.length; i++) {
				if ((checks[i] as HTMLInputElement).value != "JavaScript_key")
					(checks[i] as HTMLInputElement).checked = selectAllVal.checked;
			}
		};

		// this.updateDevSceneCheckState();

		checks.forEach((check) => {
			check.addEventListener('click', () => {
				this.updateDevSceneCheckState();
			});
		});

		for (var i = 0; i < elements.length; i++) {
			elements[i].addEventListener("change", async (event) => {
				// 根据选中不同的checkbox，显示不同输出；
				const target = event.target as HTMLInputElement;
				if (target!.checked) {
					var selectedValue = target.value;
					var firstClassList = arg["first_class_list"];
					if (selectedValue === "selectAll") {
						for (let key in firstClassList) {
							if (key.endsWith("_key") && key != "JavaScript_key") {
								this.configList[key] = arg["second_class"][key];
							}
						}
					} else {
						this.configList[selectedValue] = arg["second_class"][selectedValue];
					}
				} else {
					var selectedValue = target.value;
					if (selectedValue === "selectAll") {
						this.configList = {};
					} else {
						delete this.configList[selectedValue];
					}
				}

				//页面更新
				this.extList = [];
				this.depList = [];
				this.scriptList = [];
				if (Object.keys(this.configList).length > 0) {
					this.nextBtn!.disabled = false;
				} else {
					this.nextBtn!.disabled = true;
				}

				for (let key in this.configList) {
					for (let val of this.configList[key]["ext-list"]) {
						this.extList.push(val);
					}
				}
				this.extList = [...new Set(this.extList)];

				for (let key in this.configList) {
					for (let val of this.configList[key]["script-list"]) {
						this.scriptList.push(val);
					}
				}

				for (let key in this.configList) {
					let tDepList = this.configList[key]["pkg-list"];
					//暂时只做deb包的处理
					// if (tDepList["rpm"]) {
					// 	for (let val of tDepList["rpm"]) {
					// 		depList.push(key);
					// 	}
					// }
					// else {
					// 	for (let key in tDepList["deb"]) {
					// 		depList.push(key);
					// 	}
					// }
					if (tDepList["deb"]) {
						for (let key in tDepList["deb"]) {
							this.depList.push(key);
						}
					}
				}
				this.depList = [...new Set(this.depList)];


				var SelectedDatas = {
					configList: this.configList,
					extList: this.extList,
					depList: this.depList,
					scriptList: this.scriptList
				}

				await ipcRenderer.invoke('kylinide.installWizard.msg.deplist', SelectedDatas);
				console.log("deplist SelectedDatas:", SelectedDatas);
				if (this.depList.length > 0) {
					formattedDoc = '<h2>软件列表：</h2>';
					formattedDoc += Object.values(this.depList).map(element => `<h4>${element}</h4>`).join('');
				}
				else
					formattedDoc = '';
				if (this.extList.length > 0) {
					formattedDoc += '<h2>插件列表：</h2>';
					formattedDoc += this.extList.map(element => `<h4>${element}</h4>`).join('');
				} else {
					formattedDoc += '';
				}
				document.getElementById("outputPre")!.innerHTML = formattedDoc;
			});
		}
	}

	//根据key值获取value
	getNameFromKey(key: any) {
		let name = '';
		if (this.firstClassList.hasOwnProperty(key)) {
			name = this.firstClassList[key]['zh_cn'];
		}
		return name;
	}

	//获取开发场景安装状态
	checkKeyInstalledSucc(key: any, configList: any, extInstallState: any) {
		let flagjson = 0;
		for (let depname in configList[key]['pkg-list']['deb']) {
			if (extInstallState.get(depname) != 12) {
				flagjson++;
			}
		}
		//检查某个开发场景的插件列表是否全部安装成功
		for (let extname of configList[key]['ext-list']) {
			if (extInstallState.get(extname) != 12) {
				flagjson++;
			}
		}
		//检查某个开发场景的脚本是否全部安装成功
		for (let scriptname of configList[key]['script-list']) {
			if (extInstallState.get(scriptname['file_name']) != 15) {
				flagjson++;
			}
		}
		if (flagjson > 0) {
			return false;
		} else {
			this.reloadWindowFlag = 1;
			return true;
		}
	}
	//检查某个开发场景是否全部安装成功
	//return -1: 全部失败
	//  0:部分失败
	//  1:全部成功
	checkKeyInstalledInfo(key: any, configList: any, extInstallState: any) {
		let flagVSIX = this.checkKeyInstalledVSIX(key, configList, extInstallState);
		let flagSoft = this.checkKeyInstalledSoft(key, configList, extInstallState);
		let flagScript = this.checkKeyInstalledScript(key, configList, extInstallState);
		if (flagVSIX === 1 && flagSoft === 1 && flagScript === 1) {
			return 1;
		} else if (flagVSIX === -1 && flagSoft === -1 && flagScript === -1) {
			return -1;
		} else return 0;
	}
	//检查某个开发场景的系统基础软件是否全部安装成功
	//return -1: 全部失败
	//  0:部分失败
	//  1:全部成功

	checkKeyInstalledScript(key: any, configList: any, extInstallState: any) {
		let flagFail = 0;
		let flagSucc = 0;
		//检查某个开发场景的脚本是否全部安装成功
		for (let scriptname of configList[key]['script-list']) {
			if (extInstallState.get(scriptname['file_name']) != 15) {
				flagFail++;
			} else {
				flagSucc++;
			}
		}
		if (flagFail === 0 && flagSucc >= 0) {
			this.reloadWindowFlag = 1;
			return 1;
		}
		if (flagFail > 0 && flagSucc === 0) {
			return -1;
		} else {
			this.reloadWindowFlag = 1;
			return 0;
		}

	}
	//检查某个开发场景的系统基础软件是否全部安装成功
	//return -1: 全部失败
	//  0:部分失败
	//  1:全部成功
	checkKeyInstalledSoft(key: any, configList: any, extInstallState: any) {
		let flagFail = 0;//失败
		let flagSucc = 0;
		for (let depname in configList[key]['pkg-list']['deb']) {
			if (extInstallState.get(depname) != 12) {
				flagFail++;
			} else {
				flagSucc++;
			}
		}
		if (flagFail === 0 && flagSucc >= 0) {
			this.reloadWindowFlag = 1;
			return 1;
		}
		if (flagFail > 0 && flagSucc === 0) {
			return -1;
		} else {
			this.reloadWindowFlag = 1;
			return 0;
		}

	}

	//检查某个开发场景的插件列表是否全部安装成功
	//return -1: 全部失败
	//  0:部分失败
	//  1:全部成功
	checkKeyInstalledVSIX(key: any, configList: any, extInstallState: any) {
		let flagFail = 0;//失败
		let flagSucc = 0;
		for (let extname of configList[key]['ext-list']) {
			if (extInstallState.get(extname) != 12) {
				flagFail++;
			} else {
				flagSucc++;
			}
		}
		if (flagFail === 0 && flagSucc >= 0) {
			this.reloadWindowFlag = 1;
			return 1;
		}
		if (flagFail > 0 && flagSucc === 0) {
			return -1;
		} else {
			this.reloadWindowFlag = 1;
			return 0;
		}
	}
	//检查是否所有的软件包，插件，脚本均已成功
	checkAllInstalledSucc(extInstallState: any) {
		let flag = 0;
		for (let value of extInstallState.values()) {
			if (value != 12 && value != 15) {
				flag++;
				break;
			}
		}
		return flag > 0 ? false : true;
	}



	//发送执行脚本请求
	checkScripts(msg: any) {
		for (let obj of this.scriptList) {
			if (obj["postin"] == msg.depName) {
				if (msg.type === "depInstallSucc") {
					const installMsg = {
						type: "installScript",
						extList: this.extList,
						depList: this.depList,
						script: obj
					};
					ipcRenderer.send("kylinide.installWizard.msg.process", installMsg);
				} else if (msg.type === "depInstallFail") {
					this.extInstallState.set(obj['file_name'], 16);
				}

			}
		}
	}

	getKeyByValue(value: string, map: any) {
		const entries = Object.entries(map);
		for (const [key, val] of entries) {
			if (val === value) {
				return key;
			}
		}
		return undefined;
	}

	removeAllListeners() {
		// ipcRenderer.removeAllListeners('init-data');
		ipcRenderer.removeListener('kylinide.installWizard.init', this.listenerInit);
		// ipcRenderer.removeAllListeners('kylinide.installWizard.justDownLoad');
		// ipcRenderer.removeAllListeners('message-to-jsb');
		ipcRenderer.removeListener('kylinide.installWizard.msg', this.listenerMsg);
		ipcRenderer.removeListener('kylinide.installWizard.removeFileLister', this.listenerRemoveFileLister);
		ipcRenderer.removeListener('kylinide.installWizard.Auth', this.listenerAuth);
		ipcRenderer.removeListener('kylinide.installWizard.cancelInstall', this.listenerCancelInstall);
		ipcRenderer.removeListener('kylinide.installWizard.initdata', this.listenerInitData);
	}
}

class EventInvokeCheck {

	private lastInvokeTime: number;			// 上一次触发时间
	private invokeInterval: number;			// 触发间隔, 单位毫秒, 在此时间间隔内不再触发

	constructor(invokeInterval: number) {
		this.lastInvokeTime = -1;
		this.invokeInterval = invokeInterval;
	}

	public canInvoke(): boolean {
		if (this.invokeInterval <= 0) {
			return true;
		}

		const now = Date.now();
		if (this.lastInvokeTime < 0) {
			this.lastInvokeTime = now;
			return true;
		}

		if (now - this.lastInvokeTime > this.invokeInterval) {
			this.lastInvokeTime = now;
			return true;
		}

		return false;
	}
}

export function startup(configuration: DeployWindowConfiguration): void {
	// const platformClass = configuration.data.platform === 'win32' ? 'windows' : configuration.data.platform === 'linux' ? 'linux' : 'mac';
	// mainWindow.document.body.classList.add(platformClass); // used by our fonts
	// createCodiconStyleSheet();
	// applyZoom(configuration.data.zoomLevel);
	new deployWindow(configuration.windowId);
}


